# -*- coding: utf-8 -*-
import os
import pandas as pd
import xlrd
import requests
from Config.LOG import Log
import allure

LOG = Log()
log = LOG.log2()

"""
读取后未考虑格式
"""


def get_file_path(FileName):
    """
    获取 文件的路径
    :param FileName: 文件名称（带后缀）
    :return: file_path 文件路径
    """
    # 指定查找范围
    current_dir = os.path.dirname(os.path.abspath(__file__))  # 获取当前项目的路径
    # 获取指定目录下所有文件的路径
    for root, dirs, files in os.walk(current_dir):  # 遍历查找范围下所有目录
        for file in files:
            if file == FileName:
                # 拼接文件路径
                file_path = os.path.join(root, file)
                # 获取文件的绝对路径
                absolute_path = os.path.abspath(file_path)
                # 打印文件路径
                file_path = absolute_path.replace('\\', '\\\\')
                return file_path


def excel_read(FileName, SheetNum=0, KeyNum=0):
    """
    读取excel中每一行的参数，输出字典格式（dict）；后发送request进行接口请求
    默认第一行为字典的key
    默认非第一行为字段的value
    :param FileName: excel文件名称，带后缀
    :param KeyNum: Key值所在行数
    :param SheetNum:第几个sheet页
    :return:
    """
    with allure.step(f"打开excel文件：{FileName}；选择第{SheetNum}个sheet；第{KeyNum}为字典的key"):
        try:
            file_path = get_file_path(FileName)
            excel = xlrd.open_workbook(rf'{file_path}')  # 打开Excel文件
            sheet = excel.sheet_by_index(SheetNum)  # 选择第几个sheet

            nows = sheet.nrows  # 有效行数
            key = sheet.row_values(KeyNum)  # dict的key值

            data = {}
            dicts_list = []
            for i in range(nows - (KeyNum + 1)):
                value = sheet.row_values(i + (KeyNum + 1))  # dict 的value值
                data.update(zip(key, value))
                dicts_list.append(data.copy())
            return dicts_list
        except Exception as e:
            log.error(e)
            raise e


def excel_read2(FileName, SheetName, KeyNum=0):
    """
    读取excel中每一行的参数，输出字典格式（dict）；后发送request进行接口请求
    默认第一行为字典的key
    默认非第一行为字段的value
    :param FileName: excel文件名称，带后缀
    :param SheetName: sheet名称
    :param KeyNum: Key值所在行数
    :return:
    """
    with allure.step(f"打开excel文件：{FileName}；选择sheet:{SheetName}；第{KeyNum}为字典的key"):
        try:
            file_path = get_file_path(FileName)
            dict_list = pd.read_excel(file_path, sheet_name=f"{SheetName}", header=KeyNum).to_dict(orient='records')
            return dict_list
        except Exception as e:
            log.error(e)
            raise e


def request1(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None,
             allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None, json=None):
    if method is None:
        log.error("无接口类型")
        raise ("无接口类型")
    if url is None:
        log.error("无接口网址")
        raise ("无接口网址")
    if params == '' or params == None:
        params = None
    if data == '' or data == None:
        data = None
    if headers == '' or headers == None:
        headers = None
    if cookies == '' or cookies == None:
        cookies = None
    if files == '' or files == None:
        files = None
    if auth == '' or auth == None:
        auth = None
    if timeout == '' or timeout == None:
        timeout = None
    if allow_redirects == '' or allow_redirects == None:
        allow_redirects = True
    if proxies == '' or proxies == None:
        proxies = None
    if hooks == '' or hooks == None:
        hooks = None
    if stream == '' or stream == None:
        stream = None
    if verify == '' or verify == None:
        verify = None
    if cert == '' or cert == None:
        cert = None
    if json == '' or json == None:
        json = None
    with requests.sessions.session() as session:
        return session.request(method=method, url=url, params=params, data=data, headers=headers, cookies=cookies,
                               files=files, auth=auth, timeout=timeout,
                               allow_redirects=allow_redirects, proxies=proxies, hooks=hooks, stream=stream,
                               verify=verify, cert=cert, json=json)


def request_excel(FileName, SheetName, KeyNum):
    with allure.step(f"request直接请求{FileName}文件中接口信息"):
        params = excel_read(FileName, SheetName, KeyNum)
        return [request1(*params[i]) for i in range(len(params))]


def request_excel2(FileName, SheetNum, KeyNum):
    with allure.step(f"request直接请求{FileName}文件中接口信息"):
        params = excel_read2(FileName, SheetNum, KeyNum)
        return [request1(*params[i]) for i in range(len(params))]
